package com.ruoyi.chat.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.chat.config.RabbitConfig;
import com.ruoyi.chat.domain.ChatMessage;
import com.ruoyi.chat.service.IChatMessageService;
import com.ruoyi.common.core.dto.ChatMsg;
import com.ruoyi.common.core.enums.YesNoEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Date;
import java.time.ZoneId;

@Slf4j
@Component
public class ChatMessageConsumer {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private IChatMessageService iChatMessageService;
    @Resource
    private RabbitConfig rabbitConfig;
    @RabbitListener(queues = "${mq.CHAT_TOPIC}")
    protected void consumer(Message message, Channel channel) {

    log.info("topic:{},接收到消息,{}", rabbitConfig.chatTopic, message);
    ChatMsg chatMsg = JSON.parseObject(message.getBody(), ChatMsg.class);
    ChatMessage chatMessage = buildChatMessage(chatMsg);
    int i = iChatMessageService.insertChatMessage(chatMessage);
    if (i > 0) {
        rabbitTemplate.convertAndSend(rabbitConfig.chatExchange, rabbitConfig.chatAckTopic, JSON.toJSONString(chatMsg));
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    }
    private ChatMessage buildChatMessage(ChatMsg chatMsg){
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setIsRead(YesNoEnum.NO.getNumCode());
        chatMessage.setChatTime(Date.from(chatMsg.getChatTime().atZone(ZoneId.systemDefault()).toInstant()));
        chatMessage.setMsgType(Long.valueOf(chatMsg.getMsgType()));
        chatMessage.setReceiverId(chatMsg.getReceiverId());
        chatMessage.setSenderId(chatMsg.getSenderId());
        chatMessage.setMsg(chatMsg.getMsg());
        return chatMessage;
    }
}
